//
//  FlatDatePicker.m
//  PhongThuyHuongNha
//
//  Created by Le Anh Tai on 9/29/13.
//  Copyright (c) 2013 Le Anh Tai. All rights reserved.
//

#import <QuartzCore/QuartzCore.h>
#import "FlatDatePicker.h"
#import "Utility.h"
#import "PhongThuy/FengShuiCore.h"

#define NUMBER_OF_COLLUMN 4
#define NUMBER_OF_ROW 5

#define COLLUMN_TYPE 0
#define COLLUMN_DAY 1
#define COLLUMN_MONTH 2
#define COLLUMN_YEAR 3

#define ROW_DUONG_LICH 0
#define ROW_AM_LICH 1

#define HEIGHT_ROW 35
#define HEIGHT_TOOLBAR 44
#define WIDTH_COLLUMN_TYPE 0.4
#define WIDTH_COLLUMN_DAY 0.2
#define WIDTH_COLLUMN_MONTH 0.2
#define WIDTH_COLLUMN_YEAR 0.2

#define TEXT_COLOR [UIColor whiteColor]

@implementation FlatDatePicker

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        [self initialize];
    }
    
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self)
    {
        [self initialize];
    }
    
    return self;
}

- (void)initialize
{
    [self removeContent];
    [self fillData];
    [self initializeContents];
    
    self.backgroundColor = [UIColor blackColor];
}

- (UITableView*)tableViewAtCollumn:(NSInteger)collumn
{
    if (_tableViews.count < collumn)
    {
        return nil;
    }
    
    return [_tableViews objectAtIndex:collumn];
}

- (NSArray*)getArrayAtCollumn:(NSInteger)collumn
{
    return [Utility getObject:_dayMonthYears atIndex:collumn];
}

- (NSInteger) selectedRowInCollumn:(NSInteger)collumn
{
    
    return [[_selectedRowIndexes objectAtIndex:collumn] integerValue];
}

- (id) selectedValueInCollumn:(NSInteger)collumn
{
    NSArray *dateArray = [self getArrayAtCollumn:collumn];
    NSInteger selectedRowIndex = [self selectedRowInCollumn:collumn];
    return [Utility getObject:dateArray atIndex:selectedRowIndex];
}

- (void)selectRow:(NSInteger)row inCollumn:(NSInteger)collumn animated:(BOOL)animated
{
    [_selectedRowIndexes replaceObjectAtIndex:collumn withObject:[NSNumber numberWithInteger:row]];
    
    UITableView *tableView = [self tableViewAtCollumn:collumn];
    
    const CGPoint alignedOffset = CGPointMake(0, row*HEIGHT_ROW - tableView.contentInset.top);
    [tableView setContentOffset:alignedOffset animated:animated];
    
    if (collumn == COLLUMN_TYPE || collumn == COLLUMN_MONTH)
    {
        [self reloadDays];
    }
}

- (void)reloadDays
{
    NSDate *date = [self getDate];
    int numberOfDay;
    
    if ([self selectedRowInCollumn:COLLUMN_TYPE] == ROW_DUONG_LICH)
    {
        numberOfDay = [FengShuiCore numberOfDaySunInMonth:date.month year:date.year];
//        NSLog(@"number of day duong lich %d", numberOfDay);
    }
    else
    {
        numberOfDay = [FengShuiCore numberOfDayLunarInMonth:date.month year:date.year];
//        NSLog(@"number of day am lich %d", numberOfDay);
    }
    
    NSMutableArray *days = [[NSMutableArray alloc] init];
    for (int i  = 1; i <= numberOfDay; i++)
    {
        [days addObject:[NSString stringWithFormat:@"%d",i]];
    }
    
    [_dayMonthYears replaceObjectAtIndex:COLLUMN_DAY withObject:days];
    
    int selectedRowDay = [self selectedRowInCollumn:COLLUMN_DAY];
    
    UITableView *tableDays = [_tableViews objectAtIndex:COLLUMN_DAY];
    [tableDays reloadData];
    
    if (selectedRowDay >= days.count)
    {
        [self selectRow:days.count - 1 inCollumn:COLLUMN_DAY animated:YES];
    }
}

-(void) reloadData
{
    for (UITableView *table in _tableViews)
    {
        [table reloadData];
    }
}

- (NSInteger)collumnIndexFromTableView:(UITableView *)tableView
{
    return [_tableViews indexOfObject:tableView];
}

- (NSInteger) numberOfRowsInCollumn:(NSInteger)collumn
{
    return [[self getArrayAtCollumn:collumn] count];
}

- (NSString*) getTextAtRow:(NSInteger)row collumn:(NSInteger)collumn
{
    NSArray *dateArray = [self getArrayAtCollumn:collumn];
    return [Utility getObject:dateArray atIndex:row];
}

- (void)alignTableViewToRowBoundary:(UITableView *)tableView
{
    const CGPoint relativeOffset = CGPointMake(0, tableView.contentOffset.y + tableView.contentInset.top);
    const NSUInteger row = round(relativeOffset.y / HEIGHT_ROW);
    
    const NSInteger collumn = [self collumnIndexFromTableView:tableView];
    [self selectRow:row inCollumn:collumn animated:YES];
    
    if ([_delegate respondsToSelector:@selector(datePicker:didSelectDate:)])
    {
        [self.delegate datePicker:self didSelectDate:[self getDate]];
    }
}

- (void)setFrame:(CGRect)frame
{
    frame.size = CGSizeMake(frame.size.width, HEIGHT_ROW*NUMBER_OF_ROW + (_isShowHeader?HEIGHT_TOOLBAR:0));
    [super setFrame:frame];
    
    if (_isShowHeader)
    {
        _toolbarView.frame = RECT(0, 0, self.width, HEIGHT_TOOLBAR);
        _okButton.frame = RECT(_toolbarView.width - 55, 5, 50, _toolbarView.height - 10);
        _titleLabel.frame = RECT(0, 0, _toolbarView.width, _toolbarView.height);
    }
    
    _separatorToolbarContent.frame = RECT(0, _toolbarView.height - 2, _toolbarView.width, 2);
    
    _contentView.frame = RECT(0, _toolbarView.bottom, self.width, self.height - _toolbarView.bottom);
    
    _selectionView.frame = RECT(0, HEIGHT_ROW*(NUMBER_OF_ROW/2), _contentView.width, HEIGHT_ROW);
    
    [self setFrameTableViews];
    
    [self setFrameShadowViews];
}

- (void)setFrameTableViews
{
    UITableView *tableType = [self tableViewAtCollumn:COLLUMN_TYPE];
    UITableView *tableDay = [self tableViewAtCollumn:COLLUMN_DAY];
    UITableView *tableMonth = [self tableViewAtCollumn:COLLUMN_MONTH];
    UITableView *tableYear = [self tableViewAtCollumn:COLLUMN_YEAR];
    
    tableType.frame = RECT(0, 0, self.width*WIDTH_COLLUMN_TYPE, _contentView.height);
    tableDay.frame = RECT(tableType.right, 0, self.width*WIDTH_COLLUMN_DAY, _contentView.height);
    tableMonth.frame = RECT(tableDay.right, 0, self.width*WIDTH_COLLUMN_MONTH, _contentView.height);
    tableYear.frame = RECT(tableMonth.right, 0, _contentView.width - tableMonth.right, _contentView.height);
}

- (void)setFrameShadowViews
{
    _topShadowView.frame = RECT(0.0f, 0.0f, _contentView.width, _contentView.height*1/3);
    for (CAGradientLayer *layer in _topShadowView.layer.sublayers)
    {
        layer.frame = _topShadowView.bounds;
    }
    
    _bottomShadowView.frame = RECT(0.0f, _contentView.height-_contentView.height*1/3, _contentView.width, _contentView.height*1/3);
    for (CAGradientLayer *layer in _bottomShadowView.layer.sublayers)
    {
        layer.frame = _bottomShadowView.bounds;
    }
}

#pragma mark - Content managemet

- (void)initializeContents
{
    [self initializeToolBarView];
    
    [self initializeTableViews];
    
    [self initializeShadowTopBottom];
    
    [self initializeSeparators];
    
    [self initializeSelectionView];
}

- (void)initializeSelectionView
{
    _selectionView = [[UIView alloc] init];
    _selectionView.backgroundColor = [UIColor redColor];
    _selectionView.alpha = 0.20;
    _selectionView.userInteractionEnabled = NO;
    [_contentView addSubview:_selectionView];
}

- (void)initializeTableViews
{
    _contentView = [[UIView alloc] init];
    _contentView.backgroundColor = [UIColor clearColor];
    [self addSubview:_contentView];
    
    _tableViews = [[NSMutableArray alloc] init];
    _selectedRowIndexes = [[NSMutableArray alloc] init];
    
    for (NSInteger i = 0; i<NUMBER_OF_COLLUMN; ++i)
    {
        UITableView *table = [[UITableView alloc] init];
        table.separatorStyle = UITableViewCellSeparatorStyleNone;
        table.showsVerticalScrollIndicator = NO;
        table.contentInset = UIEdgeInsetsMake(HEIGHT_ROW*(NUMBER_OF_ROW/2), 0, HEIGHT_ROW*(NUMBER_OF_ROW/2), 0);
        table.backgroundColor = [UIColor clearColor];
        
        table.dataSource = self;
        table.delegate = self;
        [_contentView addSubview:table];
        
        [_tableViews addObject:table];
        [_selectedRowIndexes addObject:[NSNumber numberWithInteger:0]];
    }
}

- (void)initializeShadowTopBottom
{
    if (_topShadowView == nil)
    {
        _topShadowView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, _contentView.width, _contentView.height*1/3)];
        //[v setBackgroundColor:[UIColor greenColor]];
        CAGradientLayer *gradient = [CAGradientLayer layer];
        gradient.frame = _topShadowView.bounds;
        gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor blackColor] CGColor], (id)[[UIColor clearColor] CGColor], nil];
        [_topShadowView.layer insertSublayer:gradient atIndex:0];
        [_topShadowView setUserInteractionEnabled:NO];
        
        [_contentView addSubview:_topShadowView];
        
        _bottomShadowView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, _contentView.height-_contentView.height*1/3, _contentView.width, _contentView.height*1/3)];
        //[v setBackgroundColor:[UIColor greenColor]];
        CAGradientLayer *gradient2 = [CAGradientLayer layer];
        gradient2.frame = _bottomShadowView.bounds;
        gradient2.colors = [NSArray arrayWithObjects:(id)[[UIColor clearColor] CGColor], (id)[[UIColor blackColor] CGColor], nil];
        [_bottomShadowView.layer insertSublayer:gradient2 atIndex:0];
        [_bottomShadowView setUserInteractionEnabled:NO];
        
        [_contentView addSubview:_bottomShadowView];
    }
}

- (void)initializeToolBarView
{
    _isShowHeader = YES;
    
    _toolbarView = [[UIView alloc] init];
    _toolbarView.backgroundColor = [UIColor clearColor];
    [self addSubview:_toolbarView];
    
    //ok button
    _okButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_okButton addTarget:self action:@selector(okButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    [_okButton setTitle:@"OK" forState:UIControlStateNormal];
    [_okButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_okButton setBackgroundImage:[Utility setBackgroundImageByColor:COLOR_WHITE withFrame:RECT(0, 0, 2, 2)] forState:UIControlStateNormal];
    [_okButton setBackgroundImage:[Utility setBackgroundImageByColor:COLOR_ORANGE withFrame:RECT(0, 0, 2, 2)] forState:UIControlStateHighlighted];
    [_toolbarView addSubview:_okButton];
    
    //title
    _titleLabel = [[UILabel alloc] init];
    _titleLabel.textAlignment = NSTextAlignmentCenter;
    _titleLabel.font = FONT_HELVETICANEUE(18);
    _titleLabel.textColor = [UIColor whiteColor];
    _titleLabel.backgroundColor = [UIColor clearColor];
    [_toolbarView addSubview:_titleLabel];
}

- (void)initializeSeparators
{
    //separtor toolbar content
    _separatorToolbarContent = [[LineView alloc] init];
    [_toolbarView addSubview:_separatorToolbarContent];
}

- (void)removeContent
{
    // remove tables
    for (UITableView *table in _tableViews)
    {
        [table removeFromSuperview];
    }
    
    _tableViews = nil;
    
    // remove indexes
    _selectedRowIndexes = nil;
    
    //selection view
    [_selectionView removeFromSuperview];
    
    [self removeAllSubviews];
}

- (void)okButtonPressed
{
    if ([_delegate respondsToSelector:@selector(datePickerDidPressedOkButton:)])
    {
        [_delegate datePickerDidPressedOkButton:self];
    }
}

#pragma mark - Date Configuration

- (void)fillData
{
    NSArray *type = @[@"Dương Lịch",@"Âm Lịch"];
    
    NSArray *days = @[@"01",@"02",@"03",@"04",@"05",@"06",@"07",@"08",@"09",@"10",@"11",@"12",@"13",@"14",@"15",@"16",@"17",@"18",@"19",@"20",@"21",@"22",@"23",@"24",@"25",@"26",@"27",@"28",@"29",@"30",@"31"];
    
    NSArray *months = @[@"01",@"02",@"03",@"04",@"05",@"06",@"07",@"08",@"09",@"10",@"11",@"12"];
    
    NSMutableArray *years = [[NSMutableArray alloc] init];
    for (int i = THUONG_NGUON_FROM; i <= HA_NGUON_TO; i ++)
    {
        [years addObject:[NSString stringWithFormat:@"%d", i]];
    }
    
    _dayMonthYears = [[NSMutableArray alloc] initWithArray:@[type,days,months,years]];
}


#pragma mark - Date Method

- (void)setDate:(NSDate *)date animated:(BOOL)animated
{
    NSDateComponents *dateComponents = [[NSCalendar currentCalendar] components:(NSYearCalendarUnit  | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:date];
    NSInteger day = [dateComponents day];
    NSInteger month = [dateComponents month];
    NSInteger year = [dateComponents year];
    
    [self selectRow:day-1 inCollumn:COLLUMN_DAY animated:animated];
    [self selectRow:month-1 inCollumn:COLLUMN_MONTH animated:animated];
    [self selectRow:year-THUONG_NGUON_FROM inCollumn:COLLUMN_YEAR animated:animated];
}

- (void)setIsAmLich:(BOOL)isAmLich
{
    _isAmLich = isAmLich;
    
    if (_isAmLich)
    {
        [self selectRow:ROW_AM_LICH inCollumn:COLLUMN_TYPE animated:YES];
    }
    else
    {
        [self selectRow:ROW_DUONG_LICH inCollumn:COLLUMN_TYPE animated:YES];
    }
}

- (NSString *)getType
{
    return [self selectedValueInCollumn:COLLUMN_TYPE];
}

- (NSDate*)getDate
{
    NSInteger day = [[self selectedValueInCollumn:COLLUMN_DAY] integerValue];
    NSInteger month = [[self selectedValueInCollumn:COLLUMN_MONTH] integerValue];
    NSInteger year = [[self selectedValueInCollumn:COLLUMN_YEAR] integerValue];
    
    if ([self selectedRowInCollumn:COLLUMN_TYPE] == ROW_AM_LICH)
    {
        _isAmLich = YES;
    }
    else
    {
        _isAmLich = NO;
    }
    
    return [self dateWithYear:year month:month day:day];
}

- (NSDate *)dateWithYear:(NSInteger)yearS month:(NSInteger)monthS day:(NSInteger)dayS
{
    NSDateComponents *components = [[NSDateComponents alloc] init];
    [components setYear:yearS];
    [components setMonth:monthS];
    [components setDay:dayS];
    return [[NSCalendar currentCalendar] dateFromComponents:components];
}

#pragma mark - UITableView DataSource Methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    const NSInteger collumn = [self collumnIndexFromTableView:tableView];
    return [self numberOfRowsInCollumn:collumn];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return HEIGHT_ROW;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString *cellIdentifier = @"PickerCell";
    static const NSInteger tag = 7777;
    
    const NSInteger collumn = [self collumnIndexFromTableView:tableView];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    UILabel *label = nil;
    
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        const CGRect viewRect = cell.contentView.bounds;
        
        label = [[UILabel alloc] initWithFrame:CGRectZero];
        label.backgroundColor = [UIColor clearColor];
        label.textColor = TEXT_COLOR;
        label.font = [UIFont systemFontOfSize:18.0];
        label.frame = viewRect;
        label.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        label.tag = tag;
        cell.userInteractionEnabled = YES;
        label.userInteractionEnabled = YES;
        [cell.contentView addSubview:label];
        cell.contentView.backgroundColor = self.backgroundColor;
    }
    else
    {
        label = (UILabel*)[cell.contentView viewWithTag:tag];
    }
    
    if (collumn == COLLUMN_TYPE)
    {
        label.textAlignment = NSTextAlignmentRight;
    }
    else if (collumn == COLLUMN_DAY)
    {
        label.textAlignment = NSTextAlignmentRight;
    }
    else if(collumn == COLLUMN_YEAR)
    {
        label.textAlignment = NSTextAlignmentLeft;
    }
    else
    {
        label.textAlignment = NSTextAlignmentCenter;
    }
    
    label.text = [self getTextAtRow:indexPath.row collumn:collumn];
    
    return cell;
}

#pragma mark - UITableView Delegate Methods

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    const NSInteger collumn = [self collumnIndexFromTableView:tableView];
    
    [self selectRow:indexPath.row inCollumn:collumn animated:YES];
    
    if ([_delegate respondsToSelector:@selector(datePicker:didSelectDate:)])
    {
        [self.delegate datePicker:self didSelectDate:[self getDate]];
    }
}

#pragma mark - UIScrollView Delegate Methods

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (decelerate == NO)
    {
        [self alignTableViewToRowBoundary:(UITableView *)scrollView];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [self alignTableViewToRowBoundary:(UITableView *)scrollView];
}



@end
